package com.pan.hisystem.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pan.hisystem.pojo.Drug;
import com.pan.hisystem.pojo.DrugParam;
import com.pan.hisystem.pojo.RespBean;
import com.pan.hisystem.pojo.User;
import com.pan.hisystem.service.IDrugService;
import com.pan.hisystem.service.IUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.time.LocalDate;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author qingyang
 * @since 2022-03-18
 */
@RestController
@RequestMapping("/drug")
public class DrugController {

    @Autowired
    private IDrugService drugService;
    @Autowired
    private IUserService userService;



    @ApiOperation(value = "添加药品")
    @PostMapping("/addDrug")
    public RespBean addDrug(@RequestBody Drug drug, Principal principal){
        if(principal==null){
            return RespBean.error("药房管理员未登录,请登录!");
        }
        User user =userService.getOne(new QueryWrapper<User>().eq("username",principal.getName()));
        if(user ==null){
            return RespBean.error("无该操作员!");
        }
        drug.setCreateNameid(user.getId());
        drug.setCreateDate(LocalDate.now());
        if(drugService.save(drug)){
            return RespBean.success("添加成功!");
        }
        return RespBean.error("添加失败!");
    }

    @ApiOperation(value = "获取所有药品")
    @GetMapping("/getAllDrugs")
    public List<Drug> getAllDrugs(){

        return drugService.list();
    }

    @ApiOperation(value = "更新药品")
    @PutMapping("/updateDrug")
    public RespBean updateDrug(@RequestBody Drug drug){
        if(drugService.updateById(drug)){
            return RespBean.success("更新成功!");
        }
        return RespBean.error("更新失败!");
    }

    @ApiOperation(value = "删除药品")
    @DeleteMapping("/deleteDrug/{id}")
    public RespBean deleteDrug(@PathVariable Integer id){
        if(drugService.removeById(id)){
            return RespBean.success("删除成功!");
        }
        return RespBean.error("删除失败!");
    }

}
